#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

# -------------------------------------------------------------------------- #
# Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org)             #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #
$: << File.dirname(__FILE__)

require 'xml-parser.rb'
require 'actions.rb'
require 'vboxrc'

# ** PRE-DEPLOY **

#Setting a folder to keep the domain
domain_filename=ARGV[0]
`mkdir -p $(dirname #{domain_filename})`
#Saving the domain file
f = File.new(domain_filename, "w")
f.write($stdin.read)
f.close

#opening the domain file
rc = init domain_filename
#Adding this VM and its domain to the
#domains hash
add_domain @vmname,domain_filename

#STEPS OF DEPLOY
# 1.Create machine
# 2.Modify machine with deployment params
# 3.Clone disk
# 4.Add controllers
# 5.Attach controllers-mediums
# 6.Start VM

rc = create 
rc = modify if rc == 0
if (rc!=0)
  unregister 
else
  rc = clone_disks 
  if rc != 0
    close_mediums
    unregister
  else 	
    rc = add_controllers
    if rc!=0
      close_mediums
      unregister
    else
      rc = storage_attach 
      if rc!=0
        storage_dettach 
        close_mediums
        unregister	
      else
        sleep 2
        rc = start 
      end
    end
  end 
end

# rc = open_mediums if rc == 0 Deprecated Vbox 4.0


puts @vmname
exit rc

